import re
import sets

from docutils.core import publish_parts

import sqlalchemy as sa
from sqlalchemy import orm

from quickwiki.model import meta

import quickwiki.lib.helpers as h

wikiwords = re.compile(r"\b([A-Z]\w+[A-Z]+\w+)", re.UNICODE)

def init_model(engine):
    """Call me before using any of the tables or classes in the model."""

    # Reflected tables must be defined and mapped here.
    #
    #global t_reflected
    #t_reflected = sa.Table("Reflected", meta.metadata,
    #    autoload=True, autoload_with=engine)
    #orm.mapper(Reflected, t_reflected)

    sm = orm.sessionmaker(autoflush=True, transactional=True, bind=engine)

    meta.engine = engine
    meta.Session = orm.scoped_session(sm)

# table for the pages
pages_table = sa.Table('pages', meta.metadata,
    sa.Column('title', sa.types.Unicode(40), primary_key=True),
    sa.Column('content', sa.types.Text(), default='')
)

# page class
class Page(object):
    content = None

    def __str__(self):
        return self.title

    def get_wiki_content(self):
        parts = publish_parts(self.content, writer_name="html")
        content = parts["html_body"]
        titles = sets.Set(wikiwords.findall(content))
        for title in titles:
            title_url = h.url_for(controller='page', action='index',
                                  title=title)
            content = content.replace(title, h.link_to(title, title_url))
        return content

# mapping
orm.mapper(Page, pages_table)

# Classes for reflected tables may be defined here, but the table and
# mapping itself must be done in the init_model function.
#
#table_reflected = None    # Updated by init_model().
#
#class Reflected(object):
#    pass
